/* EasyWay Game Engine
 * Copyright (C) 2006 Daniele Paggi.
 *  
 * Written by: 2006 Daniele Paggi<dshnt@hotmail.com>
 *   
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 * 
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package org.easyway.geometry2D;

public class Segment extends Retta {

	float start, end;

	// TODO: DA TOGLIERE
	public boolean U, S, B, D;

	public Segment(float k, float starty, float endy) {
		super(k);
	}

	public Segment(Point2D a, Point2D b) {
		this(a.x, a.y, b.x, b.y);
	}

	public Segment(float x, float y, float x1, float y1) {
		super(x, y, x1, y1);
		if (k == Float.NaN) { // x = k;
			start = Math.min(y, y1);
			end = Math.max(y, y1);
		} else { // y = mx + q;
			start = Math.min(x, x1);
			end = Math.max(x, x1);
		}
	}

	/**
	 * controlla se un punto appartiene alla retta
	 * 
	 * @param point
	 *            punto da testare
	 * 
	 */
	public boolean testPoint(Point2D point) {
		if (point == null)
			return false;
		if (super.testPoint(point))
			if (k == Float.NaN) { // x = k;
				if (point.getY() <= end && point.getY() >= start)
					return true;
				return false;
			} else { // y = mx + q;
				if (point.getX() <= end && point.getX() >= start)
					return true;
				return false;
			}
		return false;
	}

	/**
	 * ritorna il punto di intrsezione tra 2 segmenti
	 * 
	 * @param segment
	 * @return null or new Point2D()
	 */
	public Point2D getPoint(Segment segment) {
		Point2D point;
		if (testPoint(point = super.getPoint(segment)))
			return point;
		return null;
	}

	public boolean collision(Segment s) {
		float p[] = super.collision(s);
		if (p == null)
			return false;
		if (p[0] == Float.POSITIVE_INFINITY)
			return true;
		if (p[0] < start || p[1] > end)
			return false;
		if (p[0] < s.start || p[1] > s.end)
			return false;
		return true;
	}

}
